import { Box } from "@hope-ui/solid"
import { createEffect, createSignal, onCleanup, onMount } from "solid-js"
import { MaybeLoading } from "./FullLoading"
import * as monaco from "monaco-editor"
import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker"

// 配置worker加载路径
self.MonacoEnvironment = {
  getWorker: () => new editorWorker(),
}

export interface MonacoEditorProps {
  value: string
  onChange?: (value: string) => void
  theme: "vs" | "vs-dark"
  path?: string
  language?: string
}

export const MonacoEditorLoader = (props: MonacoEditorProps) => {
  const [loading, setLoading] = createSignal(false) // 本地加载无需等待
  return (
    <MaybeLoading loading={loading()}>
      <MonacoEditor {...props} />
    </MaybeLoading>
  )
}

export const MonacoEditor = (props: MonacoEditorProps) => {
  let monacoEditorDiv: HTMLDivElement
  let monacoEditor: monaco.editor.IStandaloneCodeEditor
  let model: monaco.editor.ITextModel

  onMount(() => {
    monacoEditor = monaco.editor.create(monacoEditorDiv!, {
      value: props.value,
      theme: props.theme,
      automaticLayout: true,
    })

    model = monaco.editor.createModel(
      props.value,
      props.language,
      props.path ? monaco.Uri.parse(props.path) : undefined,
    )

    monacoEditor.setModel(model)
    monacoEditor.onDidChangeModelContent(() => {
      props.onChange?.(monacoEditor.getValue())
    })
  })

  createEffect(() => {
    if (monacoEditor) {
      monacoEditor.setValue(props.value)
    }
  })

  createEffect(() => {
    monaco.editor.setTheme(props.theme)
  })

  onCleanup(() => {
    model?.dispose()
    monacoEditor?.dispose()
  })

  return <Box w="$full" h="70vh" ref={monacoEditorDiv!} />
}
